// 使用连通图, 把5周边的1点, 全部联通在一起, 最后的count即答案
// 需要找到5相邻的所有点, 把他们联通在一起
// 如果两个点相邻, 则可以连在一起
const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

class UnionFindSet {
    constructor(n) {
        this.count = n
        this.fa = new Array(n).fill(null).map((value, index) => index)
    }

    find(x) {
        if (this.fa[x] !== x) {
            this.fa[x] = this.find(this.fa[x])
        }
        return this.fa[x]
    }

    union(x, y) {
        let rootX = this.find(x)
        let rootY = this.find(y)
        if (rootX !== rootY) {
            this.fa[rootY] = rootX
            this.count--
        }
    }
}

let m, n;
let initArr = [];
rl.on("line", (line) => {
    if (m === undefined) {
        [m, n] = line.trim().split(" ").map(Number)
    } else {
        initArr.push(line.trim().split(" ").map(Number))
        if (initArr.length === m) {
            console.log(getResult(m, n, initArr))
            // clear
            m = n = undefined
            initArr.length = 0
        }

    }

})

function getResult(m, n, initArr) {
    // 遍历, 找到5的边界点
    let direction = [
        [0, 1],
        [0, -1],
        [-1, 0],
        [1, 0],
        [-1, 1],
        [-1, -1],
        [1, -1],
        [1, 1]
    ]

    // 遍历边界点, 进行合并
    let boundary = new Set()
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (initArr[i][j] === 5) {
                for (const [a, b] of direction) {
                    let newX = i + a
                    let newY = j + b
                    if (newX >= 0 && newX < m && newY >= 0 && newY < n) {
                        if (initArr[newX][newY] === 1) {
                            boundary.add(`${newX}-${newY}`)
                        }
                    }
                }
            }
        }
    }

    // 返回连通图的count
    let union = new UnionFindSet(boundary.size)
    boundary = Array.from(boundary)
    for (let i = 0; i < boundary.length - 1; i++) {
        for (let j = i + 1; j < boundary.length; j++) {
            const [a, b] = boundary[i].split("-").map(Number)
            const [c, d] = boundary[j].split("-").map(Number)
            if (Math.abs(a - c) <= 1 && Math.abs(b - d) <= 1) {
                union.union(i, j)
            }
        }
    }

    return union.count
}